from email import header


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   utils.py
@Time    :   2022-08-02 11:27:54
@Author  :   GuoLiuFang
@Version :   0.1
@Contact :   guoliufangking@gmail.com
@License :   (C)Copyright 2018-2022, RandomMatrix
@Desc    :   None
'''
import logging
file_handler = logging.FileHandler(filename='log.log')
stdout_handler = logging.StreamHandler()
logging.basicConfig(
    level=logging.DEBUG,
    handlers=[file_handler, stdout_handler],
    format='%(asctime)s - %(processName)s - %(name)s - %(relativeCreated)d - %(threadName)s - %(levelname)s -- %(message)s'
)

# import other libs
# %%
import torch
def iou(preds, targets, data_format="mid_point"):
    # input : preds (N, 7, 7, 4); 4 (x, y, w, h); the same with targets
    # output: N, 7, 7, 1
    # mid_point xywh, x1y1x2y2;
    # corner point
    if data_format == 'mid_point':
        w = preds[...,2:3]
        h = preds[...,3:4]
        A_x1 = preds[...,0:1] - w/2
        A_y1 = preds[...,1:2] - h/2
        A_x2 = preds[...,0:1] + w/2
        A_y2 = preds[...,1:2] + h/2
        # =====
        w = targets[...,2:3]
        h = targets[...,3:4]
        B_x1 = targets[...,0:1] - w/2
        B_y1 = targets[...,1:2] - h/2
        B_x2 = targets[...,0:1] + w/2
        B_y2 = targets[...,1:2] + h/2
    elif data_format == 'corner':
        A_x1 = preds[...,0:1]
        A_y1 = preds[...,1:2]
        A_x2 = preds[...,2:3]
        A_y2 = preds[...,3:4]
        B_x1 = targets[...,0:1]
        B_y1 = targets[...,1:2]
        B_x2 = targets[...,2:3]
        B_y2 = targets[...,3:4]
    else:
        print("NO SUPPORT DATA FORMAT")
        exit()
    # intersect over uion
    # point(c_x1, c_y1, c_x2, c_y2)
    # c_x1与已知条件之间的关系呢？或者问题转化为，c_x1该如何定义出来呢？
    c_x1 = max(A_x1, B_x1)
    c_y1 = max(A_y1, B_y1)

    c_x2 = min(A_x2, B_x2)
    c_y2 = min(A_y2, B_y2)

    # intersection area
    intersection_area = torch.clamp((c_x2 - c_x1), min=0) * torch.clamp((c_y2 - c_y1), min=0)
    A_area = torch.clamp((A_x2 - A_x1), min=0) * torch.clamp((A_y2 - A_y1), min=0)
    B_area = torch.clamp((B_x2 - B_x1), min=0) * torch.clamp((B_y2 - B_y1), min=0)
    return intersection_area / (A_area + B_area - intersection_area + 10e-6)